package org.jash.shop2111.home

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import org.jash.shop2111.entry.BannerEntry
import org.jash.shop2111.entry.Category
import org.jash.shop2111.entry.Goods
import org.jash.shop2111.mvvm.BaseViewModel
import org.jash.shop2111.utils.dao.CategoryDao
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(val categoryDao: CategoryDao) : BaseViewModel() {
    val categoriesLiveData by lazy { MutableLiveData<List<Category>>() }
    val bannerLiveData by lazy { MutableLiveData<List<BannerEntry>>() }
    fun loadCategories() {
        viewModelScope.launch {
            try {
//                Log.d("HomeViewModel", "loadCategories: ")
//                val findAll = categoryDao.findAll()
//                findAll.forEach { Log.d("HomeViewModel", "loadCategories: $it") }
//                Log.d("HomeViewModel", "loadCategories: ==============================")
//                val categories = categoryDao.findByParentId(0)
//                categories.forEach { it.data = categoryDao.findByParentId(it.id) }
//                categories.forEach {
//                    Log.d("HomeViewModel", "loadCategories: $it")
//                    Log.d("HomeViewModel", "loadCategories: ${it.data}")
//                }
                val res = service.getCategories()
                if (res.code == 200) {
                    categoriesLiveData.postValue(res.data)
                    categoryDao.save(*res.data.toTypedArray())
                    categoryDao.save(*res.data.flatMap { it.data ?: listOf() }.toTypedArray())
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
    fun loadBanner() {
        viewModelScope.launch {
            try {
                val res = service.getBanner()
                if (res.code == 200) {
                    bannerLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
}